"""
Class responsable to Rename all video files that match as
a Naruto episode and put into a temporary folder. These renamed
files will still there to maybe scrapped and moved to their final destination
"""
import os
import tempfile
import time

from EpisodeRegex import EpisodeRegex
from EpisodeUtil import EpisodeUtil


class Renamer:
    
    __DEST_DIR_PREFIX = "NSR_"
    
    def __init__(self, sourceDir, destDir=None, extensions=None):
        self.sourceDir = sourceDir
        self.renamed = []
        self.extensions = extensions
        self.__regex = EpisodeRegex(extensions)
        self.__eParser = EpisodeUtil()
        self.deepSearch = True
        #TODO Poderia ser um objeto externo para tratar pastas temporarias
        self.renameDir = destDir if destDir is not None else self.__build_tempDir()
        
    def __build_tempDir(self):
        dir = "%s_%s" % (self.__DEST_DIR_PREFIX, time.time())
        tempPath = tempfile.gettempdir()
        destDirPath = "%s\\%s" % (tempPath, dir)
        os.mkdir(destDirPath)
        return destDirPath
    
    def close(self):
        os.rmdir(self.renameDir)
                   
    def rename(self):
        for file in os.listdir(self.sourceDir):
            filePathName = os.path.join(self.sourceDir, file)
            if self.__is_dir_and_deep_search_enable(filePathName):
                self.__recursively_rename(filePathName)
            else:
                self.__try_rename_file(file)
            
    def __recursively_rename(self, filePathName):
        innerRenamer = Renamer(filePathName, self.renameDir, self.extensions)
        innerRenamer.rename()

    def __try_rename_file(self, file):
        match = self.__regex.search(file)
        if match != None:
            self.__rename_file(file, match)
        
    def __rename_file(self, fileName, match):
        episode = self.__eParser.createFromMatch(match)
        if self.__file_was_not_renamed_before(fileName, episode):
            filePath = "%s\\%s" % (self.sourceDir,fileName)
            fileRenamedPath = "%s\\%s" % (self.renameDir, episode)        
            os.rename(filePath, fileRenamedPath)
            self.__add_to_renamed(episode)  
                
    def __file_was_not_renamed_before(self, fileName, episode):
        return fileName != episode.__str__()
            
    def __add_to_renamed(self, episode):
        self.renamed.append(episode)
        
    def __is_dir_and_deep_search_enable(self, file):
        return self.deepSearch and os.path.isdir(file)